package com.erp.framework.controller.taglib;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.jsp.JspException;

import com.erp.framework.model.dao.ServiceLocator;
import com.erp.framework.util.logger.Logger;

public class CustomDescTag extends javax.servlet.jsp.tagext.TagSupport {

    private String table = null;
    private String column = null;
    private String where = null;

    public void setTable(String text) {

        this.table = text;
    }

    public void setColumn(String text) {

        this.column = text;
    }

    public void setWhere(String text) {

        this.where = text;
    }

    public int doEndTag() throws JspException {

        String rslt = "";
        Connection conn = null;
        PreparedStatement pStmt = null;
        ResultSet rs = null;
        String query = "";
        String preparedQuery = "";

        try {
            query = "SELECT " + column + " COLA FROM " + table + ((where != null && !where.equals("")) ? " WHERE " + where : "");
            preparedQuery = query;

            conn = ServiceLocator.getInstance().getDSDBConnection();
            pStmt = conn.prepareStatement(preparedQuery);
            Logger.all(this, "doEndTag(), sql=" + preparedQuery);
            rs = pStmt.executeQuery();

            if (rs != null && rs.next()) {
                rslt = (rs.getString(1) == null) ? "" : rs.getString(1).trim();
            }

            rslt = (rslt == null) ? "" : rslt;

            Logger.all(this, "doEndTag(), html=" + rslt.toString());
            pageContext.getOut().print(rslt);
        } catch (Exception e) {
            Logger.logExceptions(this, e);
            Logger.error("doEndTag(), html=" + rslt.toString());
            Logger.error("doEndTag(), sql=" + preparedQuery);
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (pStmt != null)
                    pStmt.close();
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                Logger.logExceptions(this, e);
            }
        }

        return EVAL_PAGE;
    }
}